package com.jbinfo.qingcaowan.exam.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.bana.common.util.page.PageCond;
import org.bana.common.util.page.PageCondUtil;
import org.bana.common.util.page.PageResult;
import org.springframework.stereotype.Service;

import com.jbinfo.common.utils.DataTables;
import com.jbinfo.common.utils.UUIDUtils;
import com.jbinfo.qingcaowan.common.ClonePojoUtil;
import com.jbinfo.qingcaowan.common.JSONResult;
import com.jbinfo.qingcaowan.exam.dao.CircleDao;
import com.jbinfo.qingcaowan.exam.dao.ExamScoreDao;
import com.jbinfo.qingcaowan.exam.dto.ExamCircleDTO;
import com.jbinfo.qingcaowan.exam.dto.ExamScoreDTO;
import com.jbinfo.qingcaowan.exam.entity.ExamScore;
import com.jbinfo.qingcaowan.exam.entity.ExamScoreModel;
import com.jbinfo.qingcaowan.exam.service.ExamScoreService;
import com.jbinfo.qingcaowan.security.entity.User;
import com.jbinfo.qingcaowan.user.dto.UserDTO;
import com.jbinfo.qingcaowan.user.service.UserService;

/**
 * 
 * @ClassName: RoleServiceImpl
 * @Description: TODO 角色服务实现
 * @author ZhangLei
 * @date 2016年7月5日 上午11:15:08
 */
@Service("examScoreService")
public class ExamScoreServiceImpl implements ExamScoreService {
	
	@Resource(name="userService")
	private UserService userService;
	@Resource(name="examScoreDao")
	private ExamScoreDao examScoreDao;
	
	@Resource(name="circleDao")
	private CircleDao circleDao;
	
	@Override
	public DataTables<ExamScoreModel> findByParam(ExamScoreModel examScoreModel) {
		List<ExamScoreModel> tList = examScoreDao.findByParam(examScoreModel);
		return DataTables.combinTotalRecords(tList);
	}

	
	@Override
	public void save(ExamScoreModel model) {
		verification(model, "create");
		String userCode = model.getUserCode();
		String userId = null;
		Date date = null;
		User user = userService.getByCode(userCode);
		if(null != user){
			userId = user.getUserId();
		}else{
			throw new RuntimeException("不存在该用户;");
		}
		ExamScore examScore = new ExamScore();
		examScore.setId(UUIDUtils.create());
		examScore.setUserId(userId);
		examScore.setExamId(model.getExamId());
		examScore.setExamType(model.getExamType());
		examScore.setScore(model.getScore());
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		try {
			 date=sdf.parse(model.getCreatTimeStr());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		examScore.setExamTime(date);
		examScore.setCreatTime(new Date());
		examScore.setCreatUser(userCode);
		examScoreDao.insert(examScore);
	}

	
	/*@Override
	public void edit(Role role) {
		verification(role, "update");
		role.setModifiedUser(Securitys.getUserCode());
		role.setGmtModified(new Date());
		roleDao.update(role);
	}*/

	
	/*@Override
	public Role getById(String roleId) {
		return (Role) roleDao.selectByPrimaryKey(roleId);
	}
*/
	
	private void verification(ExamScoreModel examScore, String param) {
		String userId = examScore.getUserId();
		if ("update".equals(param) && (userId == null || "".equals(userId))) {
			throw new RuntimeException("用户账号不能为空;");
		}
		Integer score = examScore.getScore();
		if (score == null || "".equals(score)) {
			throw new RuntimeException("分数不能为空;");
		}
	}

	// 根据examCircle\ userId 查询用户考试得分
	@Override
	public Object findExamScore(ExamCircleDTO examCircleDTO) {
		
		ExamCircleDTO dto = circleDao.getExamScore(examCircleDTO);
		
		UserDTO userDTO = new UserDTO();
		userDTO.setUserId(examCircleDTO.getUserId());
		JSONResult userJson = (JSONResult) userService.getUserInfoById(userDTO);
		UserDTO userRet = userJson.getResultBean();
		
		// 如果该用户没参加该考试，则保存
		ExamScoreDTO queryDTO = new ExamScoreDTO();
		queryDTO.setUserId(examCircleDTO.getUserId());
		queryDTO.setExamCode(examCircleDTO.getExamCode());
		PageCond pageCond = null;
		PageCond pageCondQuery = PageCondUtil.check(pageCond);
		
		List<ExamScoreDTO> examScoreList = examScoreDao.findUserExamScore(queryDTO, pageCondQuery);
		
		if (examScoreList == null || examScoreList.isEmpty()) {
			// 保存用户考试得分
			ExamScore examScore = new ExamScore();
			examScore.setId(UUIDUtils.create());
			examScore.setUserId(examCircleDTO.getUserId());
			examScore.setExamId(dto.getId());
			examScore.setExamType(dto.getExamType());
			examScore.setScore(dto.getTotalScore());
			examScore.setCreatTime(new Date());
			examScore.setCreatUser(userRet.getUserCode());
			examScore.setExamTime(new Date());
			
			examScoreDao.insertSelective(examScore);
		}
		
		return dto;
	}
	
	// 根据userId、examCode 进行成绩查询  分页
	public Object findUserExamCode(ExamScoreDTO examScoreDTO, 
			Integer currentPage, Integer pageSize) {
		
		List<ExamScoreDTO> dtoList = new ArrayList<ExamScoreDTO>();
		
		PageCond pageCond = new PageCond(currentPage,pageSize);
		
		PageCond pageCondQuery = PageCondUtil.check(pageCond);
		
		List<ExamScoreDTO> examScoreList = examScoreDao.findUserExamScore(examScoreDTO, pageCondQuery);
		
		/*if (examScoreList == null || examScoreList.isEmpty()) {
			throw new BusinessException(BusinessExceptionCode.database_none_data, "无考试成绩数据");
		}*/
		ExamScoreDTO dto = new ExamScoreDTO();
		
		for (ExamScoreDTO examScore: examScoreList) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String strExamTime = sdf.format(examScore.getExamTime());
			
			dto = ClonePojoUtil.copyClassFromTo(examScore, ExamScoreDTO.class);
			dto.setStrExamTime(strExamTime);
			
			dtoList.add(dto);
		}
		
		Integer nExamScoreCnt = examScoreDao.findUserExamScoreCnt(examScoreDTO);
		
		pageCondQuery.setTotalCount(nExamScoreCnt);
		pageCondQuery.setPageCount(PageCondUtil.calculatePageCount(pageCondQuery));
		
		return new PageResult<ExamScoreDTO>(dtoList, pageCondQuery);
	}
}
